package com.coco.goods.service.impl;

import com.coco.common.util.IdWorker;
import com.coco.goods.mapper.ShoppingMapper;
import com.coco.goods.pojo.TbShopping;
import com.coco.goods.service.ShoppingService;
import org.redisson.Redisson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.coco.goods.service.impl
 * @Author: 张dy
 * @Date: Created in 2021/8/7 上午 11:22
 */
@Service
public class ShoppingServiceImpl implements ShoppingService {

    @Autowired
    private ShoppingMapper shoppingMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Redisson redisson;


    @Override
    public void addShopping(List<TbShopping> shoppings) {
        // 大Key 用户id  小Key 商品id
        shoppings.forEach((shopping -> {
            //获取当前购物车的商品
            TbShopping tbShopping =
                    (TbShopping) redisTemplate.boundHashOps("UserCar" + shopping.getUserId()).get("" + shopping.getGoodsId());
            //是否存在要添加到购物车的商品
            if (tbShopping != null) {
                //添加到购物车的商品购买数量
                tbShopping.setNum(tbShopping.getNum() + shopping.getNum());
                //小计
                tbShopping.setCountPrice(BigDecimal.valueOf(tbShopping.getNum() * tbShopping.getPrice().longValue()));
                //先删除缓存
                redisTemplate.boundHashOps("UserCar" + shopping.getUserId()).delete("" + shopping.getGoodsId());
                //计算好的数据重新加入缓存
                redisTemplate.boundHashOps("UserCar" + shopping.getUserId()).put("" + shopping.getGoodsId(), tbShopping);
                redisTemplate.expire("UserCar" + shopping.getUserId(), 7, TimeUnit.DAYS);
            } else {
                //初始化信息
                IdWorker idWorker = new IdWorker();
                shopping.setId(idWorker.nextId());
                shopping.setCreateTime(new Date());
                redisTemplate.boundHashOps("UserCar" + shopping.getUserId()).put("" + shopping.getGoodsId(), shopping);
                //设置过期时间
                redisTemplate.expire("UserCar" + shopping.getUserId(), 7, TimeUnit.DAYS);
            }
        }));
    }

    @Override
    public List<TbShopping> findByUserId(Long userId) {
        List<TbShopping> values =
                redisTemplate.boundHashOps("UserCar" + userId).values();
        return values;
    }

    @Override
    public void delete(Long userId, Long[] goodsId) {
        for (Long aLong : goodsId) {
            redisTemplate.boundHashOps("UserCar" + userId).delete("" + aLong);
        }
    }
}
